package cn.xuqiudong.rpc.protocol.netty.handler;

import cn.xuqiudong.rpc.common.constants.RequestType;
import cn.xuqiudong.rpc.common.model.XqdRequest;
import cn.xuqiudong.rpc.common.model.XqdResponse;
import cn.xuqiudong.rpc.common.util.JsonUtils;
import cn.xuqiudong.rpc.spring.provider.XqdServiceHolder;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cn.xuqiudong.rpc.protocol.netty.model.NettyHeader;
import cn.xuqiudong.rpc.protocol.netty.model.NettyProtocolData;

/**
 * 描述: netty Server端的的处理请求的线程
 * @author Vic.xu
 * @date 2022-02-28 10:03
 */
public class XqdChannelRunnable implements Runnable {

    private static Logger logger = LoggerFactory.getLogger(XqdChannelRunnable.class);

    private ChannelHandlerContext ctx;

    private NettyProtocolData<XqdRequest> msg;

    public XqdChannelRunnable(ChannelHandlerContext ctx, NettyProtocolData<XqdRequest> msg) {
        this.ctx = ctx;
        this.msg = msg;
    }

    @Override
    public void run() {
        logger.info("开始处理服务端的请求");
        XqdResponse response;
        try {
            // 处理数据
            Object data = XqdServiceHolder.invokeMethod(msg.getBody());
            response = XqdResponse.success(data);
        } catch (Exception e) {
            response = XqdResponse.error(e.getMessage());
        }

        //组装返回对象
        NettyProtocolData<XqdResponse> result = new NettyProtocolData();
        NettyHeader header = msg.getHeader();
        header.setRequestType(RequestType.RESPONSE.code());
        result.setHeader(header);
        result.setBody(response);
        logger.debug("服务端异步处理结果：" + JsonUtils.toJson(response));
        ctx.writeAndFlush(result);

    }
}
